//
//  MAAdvMapView.m
//  MateAdv
//
//  Created by 茶 on 2023/9/7.
//

#import "MAAdvMapView.h"
#import "MAAdvNodeView.h"
#import "MAAdvPlayerView.h"

#import <libpag/PAGView.h>

#define MAP_RATIO(value) (SCREEN_HEIGHT <= 812.0 ? (value * (SCREEN_HEIGHT / 844.0)) : value)

@interface MAAdvMapView ()

@property (nonatomic, strong) NSArray *nodeArray;
@property (nonatomic, strong) MAAdvPlayerView *hePlayer;
@property (nonatomic, strong) MAAdvPlayerView *shePlayer;
@property (nonatomic, assign, readwrite) NSUInteger heNumber;
@property (nonatomic, assign, readwrite) NSUInteger sheNumber;
@property (nonatomic, assign) NSUInteger diceNumber;

@property (nonatomic, strong) PAGView *diceView;


@property (nonatomic, assign) BOOL playerSwitch;

@end

@implementation MAAdvMapView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initMap];
        _canClick = YES;
        _playerSwitch = NO;
    }
    return self;
}

- (void)initMap {
    self.heNumber = self.sheNumber = 0;
    
    CGFloat length = MAP_RATIO(44);
    CGFloat spacing = MAP_RATIO(5);
    for (int i = 0; i < self.nodeArray.count; i++) {
        [self.nodeArray[i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(MAP_RATIO(44));
            if (i < 7) {
                make.left.mas_equalTo(18 + (spacing + length) * i);
                make.top.mas_equalTo(MAP_RATIO(34));
            } else if (i >= 7 && i < 20) {
                make.centerX.mas_equalTo(_nodeArray[6]);
                make.top.mas_equalTo(((MAAdvNodeView *)_nodeArray[6]).mas_bottom).mas_offset((spacing + (spacing + length) * (i - 7)));
            } else if (i >= 20 && i < 26) {
                make.centerY.mas_equalTo(_nodeArray[19]);
                make.right.mas_equalTo(((MAAdvNodeView *)_nodeArray[19]).mas_left).mas_offset(-((spacing + (spacing + length) * (i - 20))));
            } else if (i >= 26 && i < 37) {
                make.centerX.mas_equalTo(_nodeArray[25]);
                make.bottom.mas_equalTo(((MAAdvNodeView *)_nodeArray[25]).mas_top).mas_offset(-((spacing + (spacing + length) * (i - 26))));
            } else if (i >= 37 && i < 41) {
                make.centerY.mas_equalTo(_nodeArray[36]);
                make.left.mas_equalTo(((MAAdvNodeView *)_nodeArray[36]).mas_right).mas_offset((spacing + (spacing + length) * (i - 37)));
            } else if (i >= 41 && i < 43) {
                make.centerX.mas_equalTo(_nodeArray[40]);
                make.top.mas_equalTo(((MAAdvNodeView *)_nodeArray[40]).mas_bottom).mas_offset((spacing + (spacing + length) * (i - 41)));
            } else if (i >= 43 && i < 45) {
                make.centerY.mas_equalTo(_nodeArray[42]);
                make.right.mas_equalTo(((MAAdvNodeView *)_nodeArray[42]).mas_left).mas_offset(-((spacing + (spacing + length) * (i - 43))));
            } else if (i >= 45 && i < 47) {
                make.centerX.mas_equalTo(_nodeArray[44]);
                make.top.mas_equalTo(((MAAdvNodeView *)_nodeArray[44]).mas_bottom).mas_offset((spacing + (spacing + length) * (i - 45)));
            } else {
                make.centerY.mas_equalTo(_nodeArray[46]);
                make.left.mas_equalTo(((MAAdvNodeView *)_nodeArray[46]).mas_right).mas_offset((spacing + (spacing + length) * (i - 47)));
            }
        }];
    }
    [self initTipView];
    [self addSubview:self.shePlayer];
    [self addSubview:self.hePlayer];
    [_hePlayer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(_nodeArray.firstObject);
        make.width.mas_equalTo(MAP_RATIO(32));
        make.height.mas_equalTo(MAP_RATIO(54));
    }];
    [_shePlayer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(_nodeArray.firstObject);
        make.width.mas_equalTo(MAP_RATIO(32));
        make.height.mas_equalTo(MAP_RATIO(54));
    }];
}

- (void)initTipView {
    UIView *view = [UIView new];
    view.backgroundColor = MAColor(@"#FFBEE0");
    view.layer.cornerRadius = MARatioWidth(13);
    view.layer.borderWidth = 0.7;
    view.layer.borderColor = UIColor.whiteColor.CGColor;
    view.clipsToBounds = YES;
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(((MAAdvNodeView *)_nodeArray[30]).mas_right).ma_offset(14);
        make.bottom.equalTo(((MAAdvNodeView *)_nodeArray[23]).mas_top).ma_offset(-16);
        make.right.equalTo(((MAAdvNodeView *)_nodeArray[16]).mas_left).ma_offset(-14);
        make.top.equalTo(((MAAdvNodeView *)_nodeArray[48]).mas_bottom).ma_offset(16);
    }];
    
    UIImageView *ruleView = [UIImageView initWithName:@"Adv_Rule"];
    [view addSubview:ruleView];
    [ruleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.centerX.mas_equalTo(0);
    }];
    
    UILabel *tip1View = [UILabel new];
    tip1View.text = @"1.摇子自动走棋";
    tip1View.textColor = MAColor(kTextFlatBlackColor);
    tip1View.font = MAFontRegular(MAP_RATIO(14));
    [view addSubview:tip1View];
    [tip1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ma_offset(14);
        make.top.mas_offset(MAP_RATIO(44));
    }];
    
    UILabel *tip2View = [UILabel new];
    tip2View.text = @"2.每个格子都有任务，也可自行商量执行其他任务";
    tip2View.lineBreakMode = NSLineBreakByWordWrapping;
    tip2View.textColor = MAColor(kTextFlatBlackColor);
    tip2View.numberOfLines = 2;
    tip2View.font = MAFontRegular(MAP_RATIO(14));
    [view addSubview:tip2View];
    [tip2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ma_offset(14);
        make.right.ma_offset(-14);
        make.top.mas_offset(MAP_RATIO(68));
    }];
    
    UILabel *tip3View = [UILabel new];
    tip3View.text = @"3.先到终点者胜利";
    tip3View.textColor = MAColor(kTextFlatBlackColor);
    tip3View.font = MAFontRegular(MAP_RATIO(14));
    [view addSubview:tip3View];
    [tip3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.ma_offset(14);
        make.top.mas_offset(MAP_RATIO(112));
    }];
    
    UILabel *label = [UILabel new];
    label.text = @"点击摇骰";
    label.textColor = MAColor(@"#F52D75");
    label.font = MAFontMedium(MAP_RATIO(12));
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    
    [view addSubview:self.diceView];
    
    _diceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [view addSubview:_diceBtn];
    [_diceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-12);
        make.centerX.mas_equalTo(0);
        make.width.ma_offset(66);
        make.height.ma_offset(84);
    }];
    
    [_diceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_diceBtn);
        make.size.ma_offset(66);
        make.centerX.mas_equalTo(0);
    }];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(self.diceBtn);
    }];
    
}

- (NSUInteger)diceChange {
    NSUInteger value = 0;
    if (_canClick && _diceBtn.isUserInteractionEnabled) {
        _diceBtn.userInteractionEnabled = NO;
        _canClick = NO;
        value = arc4random() % 6 + 1;
        NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"chess%ld", value] ofType:@"pag"];
        PAGFile *file = [PAGFile Load:path];
        [_diceView setComposition:file];
        [_diceView play];
        MAWeakify(self);
        CGFloat length = file.duration / 1000000.0;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(length * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MAStrongify(self);
            [self jumpPlayerWithPlayer:self.playerSwitch ? self.shePlayer : self.hePlayer Number:value];
        });
    }
    return value;
}

- (void)jumpPlayerWithPlayer:(MAAdvPlayerView *)player Number:(NSUInteger)number {
    _playerSwitch = !_playerSwitch;
    if (number > 0) {
        _diceNumber = number;
        [self diceAnimationWithPlayer:player];
    }
}

- (void)diceAnimationWithPlayer:(MAAdvPlayerView *)player{
    CGFloat duration = 0.5f;
    CGFloat spacing = 0.06f;
    NSUInteger index = 0;
    if (player.tag == 2) {
        index = self.heNumber + 1;
    } else if (player.tag == 3) {
        index = self.sheNumber + 1;
    }
    MAWeakify(self);
    [UIView animateWithDuration:duration delay:0 usingSpringWithDamping:0.75 initialSpringVelocity:5.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        [player mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.nodeArray[index]);
            make.centerY.mas_equalTo(self.nodeArray[index]).offset(MAP_RATIO(-16));
            make.width.mas_equalTo(MAP_RATIO(32));
            make.height.mas_equalTo(MAP_RATIO(54));
        }];
        [player.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(spacing * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MAStrongify(self);
            self.diceNumber -= 1;
            if (player.tag == 2) {
                self.heNumber = index;
            } else if (player.tag == 3) {
                self.sheNumber = index;
            }
            if (self.diceNumber == 0) {
                self.diceBtn.userInteractionEnabled = YES;
                self.canClick = YES;
                if (self.sheNumber >= NODE_NUM - 1 || self.heNumber >= NODE_NUM - 1) {
                    MABlock(self.endBlock);
                    [self endEvent];
                } else {
                    MABlock(self.tipBlock, index);
                }
            } else {
                if (self.sheNumber >= NODE_NUM - 1 || self.heNumber >= NODE_NUM - 1) {
                    MABlock(self.endBlock);
                    [self endEvent];
                } else if (!self.canClick) {
                    [self diceAnimationWithPlayer:player];
                }
                
            }
        });
    }];
}

- (void)endEvent {
    self.diceBtn.userInteractionEnabled = YES;
    self.canClick = YES;
    self.sheNumber = self.heNumber = 0;
    [@[self.hePlayer, self.shePlayer] mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.nodeArray[0]);
        make.centerY.mas_equalTo(self.nodeArray[0]).offset(MAP_RATIO(-16));
        make.width.mas_equalTo(MAP_RATIO(32));
        make.height.mas_equalTo(MAP_RATIO(54));
    }];
}

- (NSArray *)nodeArray {
    if (_nodeArray) return _nodeArray;
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:NODE_NUM];
    NSUInteger index = 0;
    MAWeakify(self);
    for (int i = 0; i < NODE_NUM; i++) {
        MAAdvNodeView *node = [MAAdvNodeView new];
        [node refreshContentWithTag:i];
        if (i != 0) {
            [node refreshBackColorWithValue:index];
            index += 1;
            if (index == 4) {
                index = 0;
            }
        }
        node.clickBlcok = ^(NSUInteger index) {
            MAStrongify(self);
            MABlock(self.tipBlock, index);
        };
        [arr addObject:node];
        [self addSubview:node];
    }
    _nodeArray = arr.copy;
    return _nodeArray;
}

- (MAAdvPlayerView *)hePlayer {
    if (_hePlayer) return _hePlayer;
    _hePlayer = [[MAAdvPlayerView alloc] initWithImgName:@"Adv_He"];
    _hePlayer.tag = 2;
    return _hePlayer;
}

- (MAAdvPlayerView *)shePlayer {
    if (_shePlayer) return _shePlayer;
    _shePlayer = [[MAAdvPlayerView alloc] initWithImgName:@"Adv_She"];
    _shePlayer.tag = 3;
    return _shePlayer;
}

- (PAGView *)diceView {
    if (_diceView) return _diceView;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"chess1" ofType:@"pag"];
    PAGFile *file = [PAGFile Load:path];
    _diceView = [[PAGView alloc] initWithFrame:CGRectMake(0, 0, MARatioWidth(66), MARatioWidth(66))];
    [_diceView setComposition:file];
    [_diceView stop];
    return _diceView;
}

@end
